<?php
namespace app\admin\service;
use app\common\model\Exchange;
use app\lib\exception\BaseException;

class Statistic
{
    public $data;
    public $start_time;
    public $end_time;
    public $model;
    public $store_id;
    public function __construct()
    {
        $this->model = new Exchange();
    }
    public function setStore($store_id){
        $this->$store_id = $store_id;
    }
    public function setTime($times){
        if(empty($times['start_time']) || empty($times['end_time']))
            throw new BaseException(['msg'=>'起始时间或结束时间不能为空！']);
        $this->start_time = $times['start_time'];
        $this->end_time = $times['end_time'];
    }
    //获取每日的兑换量
    public function getDailyExchange(){
        $where = '1=1';
        if($this->store_id){
            $where .= 'e.store_id='.$this->store_id;
        }
        $where .=' AND e.consume_date is not null';
        if ($this->start_time && $this->end_time){
            $where .= ' AND e.consume_date>='.$this->start_time.' AND e.consume_date<='.$this->end_time;
        }
        $field = 'sum(p.price) as total_price,
        e.consume_date,count(1) as count';
        $res = $this->model->alias('e')->join('product p','e.product_id = p.id')->field($field)->where($where)->group('consume_date')->select();
        $res = collection($res)->toArray();
        if(!$res) return [];
        $data = [];
        foreach ($res as $k=>$v){
            $data['date'][] = $v['consume_date'];
            $data['total_price'][] = $v['total_price'];
            $data['count'][] = $v['count'];
        }
        return $data;
    }
    //获取产品占比
    public function getProductProportion(){
        $where = '1=1';
        if($this->store_id){
            $where .= 'e.store_id='.$this->store_id;
        }
        $where .=' AND e.consume_date is not null';
        if ($this->start_time && $this->end_time){
            $where .= ' AND e.consume_date>='.$this->start_time.' AND e.consume_date<='.$this->end_time;
        }
        $field = 'sum(p.price) as total_price,
        count(1) as count';
        $res = $this->model->alias('e')->join('product p','e.product_id = p.id')->field($field)->where($where)->group('p.id')->select();
        $res = collection($res)->toArray();
        if(!$res) return [];
        $data = [];
        foreach ($res as $k=>$v){
            $data['total_price'][] = $v['total_price'];
            $data['count'][] = $v['count'];
        }
        return $data;
    }
}